package com.meetingshow.weibo.actions;

import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;

import com.meetingshow.common.base.actions.BaseAction;
import com.meetingshow.common.base.uiservice.exception.BaseUIServiceException;
import com.meetingshow.privilege.actions.UserAction;
import com.meetingshow.utils.JSONUtils;
import com.meetingshow.utils.UIServiceFactory;
import com.meetingshow.weibo.jsonbean.WeiboJsonBean;
import com.meetingshow.weibo.uiservice.IUIWeiboService;
import com.meetingshow.weibo.uiservice.model.WeiboVO;
@Namespace("/weibo")
public class WeiboAction extends BaseAction {

    /**
     * 
     */
    private static final long serialVersionUID = -7358599542674559926L;

    private final static Logger logger = Logger.getLogger(UserAction.class);

    private String param;

    @Action(value = "bind")
    public String bindWeibo() {
        try {
            if (StringUtils.isBlank(param)) {
                ServletActionContext.getResponse().getWriter()
                        .write(buildErrorJson("-1", "No parameter."));
                return null;
            }
            
            JSONObject jObj = JSONObject.fromObject(param);
            WeiboJsonBean wJsonBean = (WeiboJsonBean) JSONObject.toBean(jObj, WeiboJsonBean.class);
            WeiboVO weiboVO = JSONUtils.toWeiboVO(wJsonBean);
            IUIWeiboService uiWeiboService = UIServiceFactory.getUIWeiboService();
            Integer id = uiWeiboService.saveWeibo(weiboVO);
            if (id != null)
                wJsonBean.setId(String.valueOf(id));
            
            ServletActionContext.getResponse().getWriter().write(JSONObject.fromObject(wJsonBean).toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                if (e instanceof BaseUIServiceException) {
                    ServletActionContext.getResponse().getWriter().write(buildErrorJson("-1", e.getMessage()));
                } else {
                    ServletActionContext.getResponse().getWriter().write(buildErrorJson("-1", "BindWeibo error."));
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return null;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }
}
